//
//  DateExtension.swift
//  ShiGuangJiaSwift
//
//  Created by 汪志浩 on 2022/7/17.
//

import Foundation
public extension Date{
    
              var dayInWeek : String {
        let formatter = DateFormatter()
        formatter.dateFormat = "EEEE"
        return formatter.string(from: self as Date)
    }
    
              var day: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd"
        return formatter.string(from: self as Date)
    }
    
              var month: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "MM"
        return formatter.string(from: self as Date)
    }
    
              var year: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy"
        return formatter.string(from: self as Date)
    }
    
              var dateAsPrettyString: String {
        let formatter = DateFormatter()
        formatter.dateFormat = "dd<>MM<>yyyy"
        return formatter.string(from: self as Date)
    }
}

public extension DateFormatter {
    
              convenience init (format: String) {
        self.init()
        dateFormat = format
        locale = Locale.current
    }
}

public extension String {
    
         func toDate (dateFormatter: DateFormatter) -> Date? {
        return dateFormatter.date(from: self)
    }
    
         func toDateString(inputFormatter:String, outputFormat: String)-> String?{
        guard let date = toDate(dateFormatter: DateFormatter(format: inputFormatter)) else { return nil }
        return DateFormatter(format: outputFormat).string(from: date)
    }
    
         func toDateString (dateFormatter: DateFormatter, outputFormat: String) -> String? {
        guard let date = toDate(dateFormatter: dateFormatter) else { return nil }
        return DateFormatter(format: outputFormat).string(from: date)
    }
    
    /**比较两个字符串时间 dataStr1 > dataStr2  **/
    static func sortDataString(dataStr1:String,dataStr2:String) -> Bool{
        let  data1 = dataStr1.toDate(dateFormatter: DateFormatter(format: "yyyy-MM"))
        let  data2 = dataStr2.toDate(dateFormatter: DateFormatter(format: "yyyy-MM"))
        
        if let data1 = data1,let data2 = data2 {
            let intervalStart = data1.timeIntervalSince1970
            let intervalStop = data2.timeIntervalSince1970
            
            return intervalStart > intervalStop
        }
        
        return false
    }
    
         func mapTimeString() -> String {
        if let data = self.toDate(dateFormatter: DateFormatter(format: "yyyy.MM.dd HH:mm:ss")){
            return data.timeString()
        }else{
            return self
        }
    }
    
         func mapTimestamp(inputFormatter:String)->Int64{
        if let data = self.toDate(dateFormatter: DateFormatter(format: inputFormatter)) {
            return Int64(data.timeIntervalSince1970 * 1000)
        }
        return 0
    }
}

public  extension Date {
      func toString(_ formatString : String) ->String? {
        let format = DateFormatter(format: formatString)
        return format.string(from: self)
    }
    
         func toString (dateFormatter: DateFormatter) -> String? {
        return dateFormatter.string(from: self)
    }
}

public extension Date {
    //日期显示--今天--周几
            static func detailDate24Week(time:Int64) -> String{
        let formatter = DateFormatter()
        formatter.dateStyle = DateFormatter.Style.medium
        formatter.timeStyle = DateFormatter.Style.short
        formatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
        let timeInterval = TimeInterval(time/1000)
        //获取到date
        let confromTimesp = Date.init(timeIntervalSince1970: timeInterval)
        
        var calender = NSCalendar.current
        // 设置区域
        calender.locale = Locale.init(identifier: "zh_CN")
        // 设置时区
        /*
         设置时区，设置为 GMT+8，即北京时间(+8)
         */
        calender.timeZone = TimeZone.init(abbreviation: "EST")!
        calender.timeZone = TimeZone.init(secondsFromGMT: +28800)!
        // 设定每周的第一天从星期几开始
        /*
         1 代表星期日开始，2 代表星期一开始，以此类推。默认值是 1
         */
        calender.firstWeekday = 1
        
        //ordinalityOfUnit
        let timeWeek = calender.component(.weekOfYear, from: confromTimesp)
        let systimeWeek = calender.component(.weekOfYear, from: Date.init())
        
        if calender.isDateInToday(confromTimesp) {
            
            return "今天"
        }else if calender.isDateInYesterday(confromTimesp) {
            
            return "昨天"
            
        }else if timeWeek == systimeWeek {
            let weeks = ["星期日","星期一","星期二","星期三","星期四","星期五","星期六"]
            let i = calender.ordinality(of: .weekday, in: .weekOfYear, for: confromTimesp)
            //此处一定要记得减1
            return weeks[i!-1]
            
        }else{
            return getCurrentTime(timeNum: time, format: "MM-dd")
        }
        
    }
    
    //MARK: - 时间格式转换"YYYY-MM-dd HH:mm:ss"
            static func getCurrentTime(timeNum:Int64 , format:String) -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = DateFormatter.Style.medium
        formatter.timeStyle = DateFormatter.Style.short
        formatter.dateFormat = format
        let timeInterval = TimeInterval(timeNum/1000)
        let confromTimesp = NSDate(timeIntervalSince1970:timeInterval)
        let confromTimespStr = formatter.string(from: confromTimesp as Date)
        return confromTimespStr
    }
    
              func timeString() -> String {
        let calender = Calendar.current
        let nowComponer = calender.dateComponents([.day,.month,.year], from: Date())
        let selfComponer = calender.dateComponents([.day,.month,.year], from: self)
        
        let cmps = calender.dateComponents([.day], from: selfComponer, to: nowComponer)
        if cmps.day == 0 {
            return "今日"
        }else if cmps.day == 1 {
            return "昨日"
        }else if cmps.day == 1 {
            return "前天"
        } else {
            return self.toString(dateFormatter: DateFormatter(format: "MM月dd日 ")) ?? ""
        }
    }
    
    

    /**
     * 仿照微信中的消息时间显示逻辑，将时间戳（单位：毫秒）转换为友好的显示格式.
     *
     * 1）7天之内的日期显示逻辑是：今天、昨天(-1d)、前天(-2d)、星期？（只显示总计7天之内的星期数，即<=-4d）；
     * 2）7天之外（即>7天）的逻辑：直接显示完整日期时间。
     *
     * @param dt 日期时间对象（本次被判断对象）
     * @param includeTime YES表示输出的格式里一定会包含“时间:分钟”，否则不包含（参考微信，不包含时分的情况，用于首页“消息”中显示时）
     *
     * @return 输出格式形如：“刚刚”、“10:30”、“昨天 12:04”、“前天 20:51”、“星期二”、“2019/2/21 12:09”等形式
     * @since 1.3
     */
             static func extGetWxTimeString(timeStamp:Int64) -> String {
        let date = Date(timeIntervalSince1970: TimeInterval(timeStamp / 1000))
        return date.extGetWxTimeString()
    }
    
              func extGetWxTimeString(_ includeTime: Bool = true) -> String {
        
        let kCalendar = Calendar.current
        
        // 当前时间 比我们实际时间慢了8个小时
        let currentDate = Date()
        
        let curComponents = kCalendar.dateComponents([.year, .month, .day, .weekday], from: currentDate)
        let currentYear = curComponents.year
        let currentMonth = curComponents.month
        let currentDay = curComponents.day
        
        // 目标判断时间
        let srcComponents = kCalendar.dateComponents([.year, .month, .day, .weekday], from: self)
        let srcYear = srcComponents.year
        let srcMonth = srcComponents.month
        let srcDay = srcComponents.day
        
        // 要额外显示的时间分钟
        let timeExtraStr = (includeTime ? getTimeString(date: self, format: " HH:mm") : "")
        
        // 当年
        if (currentYear == srcYear) {
            let currentTimestamp = currentDate.timeIntervalSince1970
            let srcTimestamp = self.timeIntervalSince1970
            
            // 相差时间（单位：秒）
            let delta = currentTimestamp - srcTimestamp
            
            // 当天（月份和日期一致才是）
            if(currentMonth == srcMonth && currentDay == srcDay) {
                // 时间相差60秒以内
                if (delta < 60) {
                    return "刚刚"
                }
                
                // 否则当天其它时间段的，直接显示“时:分”的形式
                return getTimeString(date: self, format: "HH:mm")
            }
            // 当年 && 当天之外的时间（即昨天及以前的时间）
            else {
                // 昨天（以“现在”的时候为基准-1天）
                let nowDate = Date()
                let yesterdayDate = Date(timeInterval: -24*60*60, since: nowDate)
                let yesterdayComponents = kCalendar.dateComponents([.year, .month, .day, .weekday], from: yesterdayDate)
                let yesterdayMonth = yesterdayComponents.month
                let yesterdayDay = yesterdayComponents.day
                
                // 前天（以“现在”的时候为基准-2天）
                let beforeYesterdayDate = Date(timeInterval: -48*60*60, since: nowDate)
                let beforeYesterdayComponents = kCalendar.dateComponents([.year, .month, .day, .weekday], from: beforeYesterdayDate)
                let beforeYesterdayMonth = beforeYesterdayComponents.month
                let beforeYesterdayDay = beforeYesterdayComponents.day
                
                // 用目标日期的“月”和“天”跟上方计算出来的“昨天”进行比较，是最为准确的（如果用时间戳差值
                // 的形式，是不准确的，比如：现在时刻是2019年02月22日1:00、而srcDate是2019年02月21日23:00，
                // 这两者间只相差2小时，直接用“delta/3600” > 24小时来判断是否昨天，就完全是扯蛋的逻辑了）
                if (srcMonth == yesterdayMonth && srcDay == yesterdayDay) {
                    return "昨天\(timeExtraStr)"// -1d
                }
                // “前天”判断逻辑同上
                else if (srcMonth == beforeYesterdayMonth && srcDay == beforeYesterdayDay) {
                    return "前天\(timeExtraStr)"// -2d
                }
                else {
                    // 跟当前时间相差的小时数
                    let deltaHour = (delta/3600)
                    
                    // 如果小于或等 7*24小时就显示星期几
                    if (deltaHour <= 7*24) {
                        let weekdays = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"]
                        // 取出的星期数：1表示星期天，2表示星期一，3表示星期二。。。。 6表示星期五，7表示星期六
                        guard let srcWeekday = srcComponents.weekday else {
                            return ""
                        }
                        
                        // 取出当前是星期几
                        let weedayDesc = weekdays[srcWeekday-1]
                        return "\(weedayDesc)\(timeExtraStr)"
                    }
                    // 否则直接显示完整日期时间
                    else {
                        return "\(getTimeString(date: self, format: "yyyy/M/d"))\(timeExtraStr)"
                    }
                }
            }
        }
        
        // 往年
        return "\(getTimeString(date: self, format: "yyyy/M/d"))\(timeExtraStr)"
    }
    
            func getTimeString(date: Date, format: String) -> String {
        let fmt = DateFormatter()
        fmt.dateFormat = format
        let rst = fmt.string(from: date)
        return rst
    }
    
           static func formatDuration(_ duration: Int , titleColor:UIColor ,titleFontSize:CGFloat,shuZiColor:UIColor ,shuZiFontSize:CGFloat) -> NSMutableAttributedString {
        let years = Int(duration / (365 * 24 * 3600))
        let months = Int((duration - Int(years) * 365 * 24 * 3600) / (30 * 24 * 3600))
        let days = Int((duration - Int(years) * 365 * 24 * 3600 - Int(months) * 30 * 24 * 3600) / (24 * 3600))
        let hours = Int((duration - Int(years) * 365 * 24 * 3600 - Int(months) * 30 * 24 * 3600 - Int(days) * 24 * 3600) / 3600)
        let minutes = Int((duration - Int(years) * 365 * 24 * 3600 - Int(months) * 30 * 24 * 3600 - Int(days) * 24 * 3600 - Int(hours) * 3600) / 60)
        let seconds = Int(duration) % 60
        
        let mut = NSMutableAttributedString(string: "倒计时",attributes: [.font:UIFont.PF_Medium(size: titleFontSize), .foregroundColor:titleColor])
        
        if years > 0 {
            
            let nian =  NSAttributedString(string: " \(years) ",attributes: [.font:UIFont.PF_Semibold(size: shuZiFontSize) , .foregroundColor:shuZiColor])
            let unit =  NSAttributedString(string: "年")
            mut.append(nian)
            mut.append(unit)
        }
        if months > 0 {
            let nian =  NSAttributedString(string: " \(months) ",attributes: [.font:UIFont.PF_Semibold(size: shuZiFontSize) , .foregroundColor:shuZiColor])
            let unit =  NSAttributedString(string: "月")
            mut.append(nian)
            mut.append(unit)
        }
        if days > 0 {
            let nian =  NSAttributedString(string: " \(days) ",attributes: [.font:UIFont.PF_Semibold(size: shuZiFontSize) , .foregroundColor:shuZiColor])
            let unit =  NSAttributedString(string: "天")
            mut.append(nian)
            mut.append(unit)
        }
        if hours > 0 {
            let nian =  NSAttributedString(string: " \(hours) ",attributes: [.font:UIFont.PF_Semibold(size: shuZiFontSize) , .foregroundColor:shuZiColor])
            let unit =  NSAttributedString(string: "时")
            mut.append(nian)
            mut.append(unit)
        }
        if minutes > 0 {
            let nian =  NSAttributedString(string: " \(minutes) ",attributes: [.font:UIFont.PF_Semibold(size: shuZiFontSize) , .foregroundColor:shuZiColor])
            let unit =  NSAttributedString(string: "分")
            mut.append(nian)
            mut.append(unit)
        }
        if seconds > 0 {
            let nian =  NSAttributedString(string: " \(seconds) ",attributes: [.font:UIFont.PF_Semibold(size: shuZiFontSize) , .foregroundColor:shuZiColor])
            let unit =  NSAttributedString(string: "秒")
            mut.append(nian)
            mut.append(unit)
        }
        
        let unit =  NSAttributedString(string: " 后失效")
        mut.append(unit)
        return mut
    }
}

public extension Date {
    
    //获取当前时间 （以毫秒为单位）
        static func getNowTimeTimestamp(time:TimeInterval) -> TimeInterval {
        let dateNow = Date(timeIntervalSince1970: time)
        let formatter = DateFormatter()
        formatter.dateFormat = "HH:mm:ss"
        formatter.timeZone = NSTimeZone(abbreviation: "Asia/Beijing") as TimeZone?
        let dateString = formatter.string(from: dateNow)
        //        print(dateString)
        //        print(secondTimeForDate(dateString))
        return secondTimeForDate(dateString)
    }
    
       static func getNowTimeTimestampInt() -> Int64 {
        return Int64(Date().timeIntervalSince1970 * 1000)
    }
    
            static func getNowTimeTimestamp() -> TimeInterval {
        return Date().timeIntervalSince1970 * 1000
    }
             static func getNowTimeTimestamp_sec() -> Int64 {
        return  Int64(Date().timeIntervalSince1970)
    }
    
    // 传入时间字符串
    static func secondTimeForDate(_ time: String) -> TimeInterval{
        var long:TimeInterval = 0
        // 时间  几分几秒 0:00  计算秒
        if time.count == 4 {
            // 获取分
            let minute = time.substring(to:1)
            // 获取秒
            let second = time.substring(from: 2)
            long = TimeInterval(minute)! * 60 + TimeInterval(second)!
            return long
        }
        // 时间  几十分几秒 00:00 计算秒
        if time.count == 5 {
            // 获取分
            let minute = time.substring(to: 2)
            // 获取秒
            let second = time.substring(from: 3)
            long = TimeInterval(minute)! * 60 + TimeInterval(second)!
            return long
        }
        // 时间 时分秒  0:00:00  计算秒
        if time.count == 7 {
            // 获取时
            let hour = time.substring(to: 1)
            // 获取分
            let minute = time.substring(from: 2, to: time.count - 3)
            // 获取秒
            let second = time.substring(from: 5)
            long = TimeInterval(hour)! * 3600 + TimeInterval(minute)! * 60 + TimeInterval(second)!
            return long
        }
        // 时间  几十时分秒  00:00:00 计算秒
        if time.count == 8 {
            // 获取时
            let hour = time.substring(to: 1)
            // 获取分
            let minute = time.substring(from: 3, to: time.count - 4)
            // 获取秒
            let second = time.substring(from: 6)
            long = TimeInterval(hour)! * 3600 + TimeInterval(minute)! * 60 + TimeInterval(second)!
            return long
        }
        return long
    }
    
            static func createDateStr(createdStr:String) -> String {
        // 2019-07-05 18:04:09
        let fmt = DateFormatter()
        fmt.dateFormat = "EEE MM dd HH:mm:ss Z yyyy"
        fmt.locale = Locale(identifier: "en")
        
        //创建时间
        guard let createDate = string2Date(createdStr) else { return "" }
        
        //获取当前时间
        let dateNow = Date()
        
        //创建时间与当前时间的时间差
        let interval = Int(dateNow.timeIntervalSince(createDate))
        //刚刚
        if interval < 60 {
            return "刚刚"
        }
        //几分钟前
        if interval < 60 * 60 {
            return "\(interval / 60)分钟前"
        }
        //几小时前
        if interval < 60 * 60 * 24 {
            return "\(interval / ( 60 * 60))小时前"
        }
        
        //获取日历对象
        let calendar = Calendar.current
        
        //昨天
        if calendar.isDateInYesterday(createDate) {
            fmt.dateFormat = "昨天 HH:mm"
            let timeStr = fmt.string(from: createDate)
            return timeStr
        }
        
        let comps = calendar.compare(createDate, to: dateNow, toGranularity: .year)
        //一年内
        if comps.rawValue < 1 {
            fmt.dateFormat = "MM-dd HH:mm"
            let timeStr = fmt.string(from: createDate)
            return timeStr
        }
        
        //一年前
        fmt.dateFormat = "yyyy-MM-dd HH:mm"
        let timeStr = fmt.string(from: createDate)
        return timeStr
    }
    
            static func string2Date(_ string:String, dateFormat:String = "yyyy-MM-dd HH:mm:ss") -> Date? {
        let formatter = DateFormatter()
        formatter.locale = Locale.init(identifier: "zh_CN")
        formatter.dateFormat = dateFormat
        let date = formatter.date(from: string)
        return date
    }
    
    //时间转时间戳 格式:2020-04-26 14:59:30
            static func dateCoversionTimeStamp(date:Date) -> TimeInterval {
        return date.timeIntervalSince1970 * 1000
    }
    
    //获取当前时间的时间戳
            static func currentDateToString() -> String {
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let timeZone = TimeZone(abbreviation: "Asia/Beijing")
        formatter.timeZone = timeZone
        let date = formatter.string(from: Date())
        return date
    }
    
    //时间戳转字符串
             static func timeStampConversionString(timeinterval:TimeInterval) -> String {
        let date = Date(timeIntervalSince1970: timeinterval / 1000)
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return formatter.string(from: date)
    }
    
             static func currentDateString() -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let dateString = formatter.string(from: Date())
        return dateString
    }
    
            static func priousDateFromDate(date:Date,day:Int) -> String {
        var comps = DateComponents()
        comps.day = day
        let calender = Calendar(identifier: Calendar.Identifier.gregorian)
        let tempDate = calender.date(byAdding: comps, to: date)
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        let dateString = formatter.string(from: tempDate ?? Date())
        
        return dateString
    }
    
            static func datesFrom(count:Int) -> [String] {
        var dates:[String] = [String]()
        let temp = count / 2
        for i in 0...temp {
            let tempDate = priousDateFromDate(date: Date(), day: i - temp - 1)
            dates.append(tempDate)
        }
        
        dates.append(contentsOf: getDatesFrom(date: Date(), count: temp))
        return dates
    }
    
           static func getDatesWith(count:Int) -> [String] {
        var dates:[String] = [String]()
        let temp = count / 2
        dates.append(contentsOf: getDatesFrom(date: Date(), count: temp))
        
        var tempDates = [String]()
        for i in 1...temp {
            let tempDate = priousDateFromDate(date: Date(), day: i - temp - 1)
            tempDates.append(tempDate)
        }
        
        tempDates.reverse()
        dates.append(contentsOf: tempDates)
        
        return dates
    }
    
    ///传入今日日期及距今的月份month
         static func priousOrLaterDateFrom(date:Date,with month:Int) -> String {
        var comps = DateComponents()
        comps.month = month
        let calender = Calendar.init(identifier: Calendar.Identifier.gregorian)
        let resultDate = calender.date(byAdding: comps, to: date) ?? Date()
        
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        
        let dateString = formatter.string(from: resultDate)
        
        return dateString
    }
    
    ///获取当前日期之前n天的日期
         static func getDatesBefore(date:Date,count:Int) -> [String] {
        var dates:[String] = [String]()
        for i in 0..<count {
            let date = priousDateFromDate(date: date, day: -i)
            dates.append(date)
        }
        return dates
    }
    
    ///获取当前日期之后n天的日期
         static func getDatesFrom(date:Date,count:Int) -> [String] {
        var dates:[String] = [String]()
        for i in 0..<count {
            let date = priousDateFromDate(date: date, day: i)
            dates.append(date)
        }
        return dates
    }
}

public  let unitFlags = Set<Calendar.Component>([.year,.month,.day,.hour,.minute,.second,.weekdayOrdinal])
public  extension Date {
    static      func currentCalendar() -> Calendar{
        let calendar = Calendar.autoupdatingCurrent
        return calendar
    }
         func jh_year() -> NSInteger{
        let components = Date.currentCalendar().dateComponents(unitFlags, from: self)
        return components.year ?? 2000
    }
         func jh_month() -> NSInteger{
        let components = Date.currentCalendar().dateComponents(unitFlags, from: self)
        return components.month ?? 1
    }
         func jh_day() -> NSInteger{
        let components = Date.currentCalendar().dateComponents(unitFlags, from: self)
        return components.day ?? 1
    }
         func jh_hour() ->NSInteger{
        let components = Date.currentCalendar().dateComponents(unitFlags, from: self)
        return components.hour ?? 0
    }
         func jh_minter() -> NSInteger{
        let components = Date.currentCalendar().dateComponents(unitFlags, from: self)
        return components.minute ?? 0
    }
         func jh_second() ->NSInteger{
        let components = Date.currentCalendar().dateComponents(unitFlags, from: self)
        return components.second ?? 0
    }
         func jh_weekend() ->NSInteger{
        let components = Date.currentCalendar().dateComponents(unitFlags, from: self)
        return components.weekday ?? 0
    }
    
    /// 日期转换成星期几
    ///
    /// - Parameter date: 日期
    /// - Returns: 星期几
    static      func getDateWeekday(date:Date) ->Int{
        //        let weekdaysTitleArr = ["周日","周一","周二","周三","周四","周五","周六"]
        let timeInterval:TimeInterval = date.timeIntervalSince1970
        let days = Int(timeInterval/86400)
        let weekday = ((days + 4)%7+7)%7
        //        return weekdaysTitleArr[weekday]
        return weekday
    }
    static      func jh_setYear(year:NSInteger,month:NSInteger,day:NSInteger,hour:NSInteger,minute:NSInteger,second:NSInteger) -> Date{
        let calendar = Date.currentCalendar()
        var components = calendar.dateComponents(unitFlags, from: Date())
        if year >= 0 {
            components.year = year
        }
        if month >= 0 {
            components.month = month
        }
        if day >= 0{
            components.day = day
        }
        if hour >= 0 {
            components.hour = hour
        }
        if minute >= 0 {
            components.minute = minute
        }
        if second >= 0 {
            components.second = second
        }
        return calendar.date(from: components)!
    }
         static func jh_setYear(year:NSInteger,month:NSInteger,day:NSInteger,hour:NSInteger,minute:NSInteger) -> Date{
        return self.jh_setYear(year: year, month: month, day: day, hour: hour, minute: minute, second: -1)
    }
    static      func jh_setYear(year:NSInteger,month:NSInteger,day:NSInteger) -> Date{
        return self.jh_setYear(year: year, month: month, day: day, hour: -1, minute: -1, second: -1)
    }
    static      func jh_setYear(year:NSInteger,month:NSInteger) -> Date{
        return self.jh_setYear(year: year, month: month, day: -1, hour: -1, minute: -1, second: -1)
    }
    static      func jh_setYear(year:NSInteger) -> Date{
        return self.jh_setYear(year: year, month: -1, day: -1, hour: -1, minute: -1, second: -1)
    }
    static      func jh_setMonth(month:NSInteger,day:NSInteger,hour:NSInteger,minute:NSInteger) -> Date{
        return self.jh_setYear(year: -1, month: month, day: day, hour: hour, minute: minute, second: -1)
    }
    static      func jh_setMonth(month:NSInteger,day:NSInteger) -> Date{
        return self.jh_setYear(year: -1, month: month, day: day, hour: -1, minute: -1, second: -1)
    }
    static      func jh_setHour(hour:NSInteger,minute:NSInteger) -> Date{
        return self.jh_setYear(year: -1, month: -1, day: -1, hour: hour, minute: minute, second: -1)
    }
    static      func setYear(year:NSInteger) -> Date{
        return self.jh_setYear(year: year)
    }
    static      func setYear(year:NSInteger,month:NSInteger) -> Date{
        return self.jh_setYear(year: year, month: month)
    }
    static      func setYear(year:NSInteger,month:NSInteger,day:NSInteger) -> Date{
        return self.jh_setYear(year: year, month: month, day: day)
    }
    static      func setYear(year:NSInteger,month:NSInteger,day:NSInteger,hour:NSInteger,minute:NSInteger) -> Date{
        return self.jh_setYear(year: year, month: month, day: day, hour: hour, minute: minute)
    }
    static      func setMonth(month:NSInteger,day:NSInteger,hour:NSInteger,minute:NSInteger) -> Date{
        return self.jh_setMonth(month: month, day: day, hour: hour, minute: minute)
    }
    static      func setMonth(month:NSInteger,day:NSInteger) -> Date{
        return self.jh_setMonth(month: month, day: day)
    }
    static      func setHour(hour:NSInteger,minute:NSInteger) -> Date{
        return self.jh_setHour(hour: hour, minute: minute)
    }
         static func jh_getDateString(date:Date,format:String) -> String{
        let components = DateFormatter()
        components.dateFormat = format
        return components.string(from: date as Date)
    }
         static func jh_getDate(dateString:String,format:String) -> Date? {
        let dateFormatter = DateFormatter()
        //        dateFormatter.locale = Locale.current
        //        dateFormatter.dateStyle = .medium
        //        dateFormatter.timeStyle = .none
        //        dateFormatter.timeZone = NSTimeZone.system
        dateFormatter.dateFormat = format
        let date = dateFormatter.date(from: dateString)
        let zone = NSTimeZone.system
        return date?.addingTimeInterval(TimeInterval(zone.secondsFromGMT(for: date!)))
    }
    static      func jh_getDaysInYear(year:NSInteger,month:NSInteger) -> Int{
        let date = Date.jh_getDate(dateString: "\(year)-\(month)", format: "yyyy-MM")
        let calendar = Calendar.init(identifier: Calendar.Identifier.gregorian)
        let range = calendar.range(of: Calendar.Component.day, in: Calendar.Component.month, for: date!)
        return range?.count ?? 0
    }
    static      func jh_getNewDate(date:Date,addDays:TimeInterval) -> Date{
        return date.addingTimeInterval(3600 * 24 * addDays) as Date
    }
    dynamic      func jh_compare(targetDate:Date,format:String) -> Bool{
        let dateStr1 = Date.jh_getDateString(date: self, format: format)
        let dateStr2 = Date.jh_getDateString(date: targetDate, format: format)
        let date1 = Date.jh_getDate(dateString: dateStr1, format: format)
        let date2 = Date.jh_getDate(dateString: dateStr2, format: format)
        if date1!.compare(date2!) == ComparisonResult.orderedDescending{
            return false
        }else if date1!.compare(date2!) == ComparisonResult.orderedAscending{
            return true
        }else{
            return true
        }
    }
    
    /// 阳历转换成g农历
    ///
    /// - Parameter solarDate: 日期
    /// - Returns: 对应的农历
         static  func solarToLuar(solarDate:Date) -> String{
        let calendar = Calendar.init(identifier: .chinese)
        let formatter = DateFormatter()
        formatter.locale = Locale(identifier: "zh_CN")
        formatter.dateStyle = .medium
        formatter.calendar = calendar
        return formatter.string(from: solarDate)
        
    }
}
